<template>
  <div class="app-container page">
    <!-- 搜索条件表单 -->
    <div class="params-form app-container" v-if="paramsForm.productStatus != 7">
      <el-form :model="paramsForm" label-width="auto" ref="paramsRef">
        <el-form-item label="成本价">
          <div class="space">
            <el-input v-model="paramsForm.minPrice" />
            -
            <el-input v-model="paramsForm.maxPrice" />
          </div>
        </el-form-item>
        <el-form-item label="是否特价" prop="isSpecialPrice">
          <el-select v-model="paramsForm.isSpecialPrice">
            <el-option
              v-for="item in paramsOption.bool_type"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="商品风格" prop="productStyle">
          <el-select v-model="paramsForm.productStyle">
            <el-option
              v-for="item in paramsOption.shop_product_style"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否定制" prop="customType">
          <el-select v-model="paramsForm.customType">
            <el-option v-for="item in customTypeList" :key="item.dictValue" :value="item.dictValue" :label="item.dictLabel" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否有模型" prop="isModel">
          <el-select v-model="paramsForm.isModel">
            <el-option
              v-for="item in paramsOption.shop_is_model"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-cascader
            style="width: 100%"
            :options="paramsOption.classify"
            v-model="paramsForm.categoryId"
            :props="{ label: 'name', value: 'categoryId' }"
            :show-all-levels="false"
            clearable
            filterable
          />
        </el-form-item>
        <el-form-item label="线上同款" prop="categoryId">
          <el-select v-model="paramsForm.isOnlineEquivalent">
            <el-option label="有" :value="1"></el-option>
            <el-option label="无" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产地筛选" prop="buinessAddressIdList">
          <el-cascader
            v-model="paramsForm.buinessAddressIdList"
            :options="area"
            :props="{
              expandTrigger: 'hover',
              value: 'cityCode',
              label: 'name',
              multiple: true
            }"
            collapse-tags
            :collapse-tags-tooltip="false"
            :max-collapse-tags="1"
            style="width: 100%"
          />
        </el-form-item>
        <div></div>
        <div class="form-btn">
          <el-button type="primary" :icon="Search" @click="init">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" plain @click="reset">重置</el-button>
        </div>
      </el-form>
    </div>
    <!-- 操作tabs以及表头 -->
    <div class="sticky" :style="{ '--margin-bottom': paramsForm.productStatus == 7 ? 0 : '15px' }">
      <el-tabs v-model="paramsForm.productStatus" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane :label="'全部(' + counts.allNum + ')'" :name="0"></el-tab-pane>
        <el-tab-pane :label="'待审核(' + counts.reviewedNum + ')'" :name="2"></el-tab-pane>
        <el-tab-pane :label="'审核驳回(' + counts.downdNum + ')'" :name="6"></el-tab-pane>
        <el-tab-pane :label="'已上架(' + counts.listingNum + ')'" :name="3"></el-tab-pane>
        <el-tab-pane :label="'即将下架(' + counts.comingDownNum + ')'" :name="4"></el-tab-pane>
        <el-tab-pane :label="'已下架(' + counts.delistNum + ')'" :name="5"></el-tab-pane>
        <el-tab-pane :label="'平台属性(' + counts.platformAttributeNum + ')'" :name="7"></el-tab-pane>
      </el-tabs>
      <PlatformAttribute v-if="paramsForm.productStatus == 7" :defaultImage="defaultImage" />
      <template v-else>
        <div class="operate">
          <el-button type="primary" plain v-if="isShow('name')" @click="showModal('nameConfig')">批量修改商品名称 </el-button>
          <el-button type="primary" plain v-if="isShow('area')" @click="openArea()">批量修改运营区域</el-button>
          <el-button type="primary" plain v-if="paramsForm.productStatus === 2" @click="handleOverrule">批量驳回 </el-button>
          <el-button type="primary" v-if="isShow('shelves')" @click="openBatch('up')">上架</el-button>
          <el-button type="primary" v-if="isShow('pass')" @click="openBatch('pass')">通过</el-button>
          <el-button type="primary" v-if="isShow('logoff')" @click="openBatch('down')">下架</el-button>
          <el-button type="primary" @click="handleDown" v-loading="exportLoding">导出商品上传数据</el-button>
          <el-input placeholder="请输入商品名称/品牌/商品分类关键词" v-model="paramsForm.search" @blur="init">
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>
        </div>
        <el-row class="table-head">
          <el-col :span="6">
            <div class="all">
              <el-checkbox @change="setCheckAll" v-model="checkAll" :indeterminate="isIndeterminate"></el-checkbox>
            </div>
            <span class="image-title">商品图</span>
            <span>商品信息</span>
          </el-col>
          <el-col :span="2"> 库存</el-col>
          <el-col :span="2"> 品牌</el-col>
          <el-col :span="2"> sku数</el-col>
          <el-col :span="3"> 价格</el-col>
          <el-col :span="3"> 上架日期</el-col>
          <el-col :span="2"> 实际销量</el-col>
          <el-col :span="2"> 状态</el-col>
          <el-col :span="2"> 操作</el-col>
        </el-row>
      </template>
    </div>
    <!-- 列表 -->
    <template v-if="paramsForm.productStatus != 7">
      <div class="table-list">
        <el-empty description="空" v-if="!data.length" />
        <el-checkbox-group v-model="checkedList">
          <div class="goods" v-for="goods in data" :key="goods">
            <div class="business-name">
              <div class="name">
                <div class="all">
                  <el-checkbox :value="goods.productId" @change="checked" />
                </div>
                <span style="cursor: default" @click="toPathPreview(goods)">{{ goods.productName }}</span>
              </div>
              <div @click="openArea(goods.productId)">
                运营区域：
                <template v-if="goods.areaList.length">
                  <el-tag type="primary">{{ goods.areaList[0]?.areaName }}</el-tag>
                  <el-tag type="primary" v-if="goods.areaList[1]">{{ goods.areaList[1]?.areaName }}</el-tag>
                </template>
                <span v-else>--未设置--</span>
              </div>
            </div>
            <el-row>
              <el-col :span="6">
                <img class="image" :src="goods.mainPicUrl || defaultImage" alt="" />
                <div class="info" style="white-space: break-spaces; word-break: break-all">
                  <div>上架类目：{{ goods.preview }}</div>
                  <div>型号：{{ goods.modeCode }}</div>
                  <div>分类：{{ goods.categoryName }}</div>
                  <div>ID：{{ goods.productId }}</div>
                  <div v-if="paramsForm.type == 4" class="red">工厂对此件商品进行了下架，请提前安排</div>
                </div>
              </el-col>
              <el-col :span="2">
                {{ goods.factoryStock }}
              </el-col>
              <el-col :span="2" style="white-space: break-spaces; word-break: break-all">
                {{ goods.brandName }}
              </el-col>
              <el-col :span="2">
                {{ goods.skuNum }}
              </el-col>
              <el-col :span="3"><span v-if="goods.isSpecialPrice == 1">特价</span>￥{{ goods.factoryLowestPrice }} </el-col>
              <el-col :span="3">
                {{ goods.listingTime }}
              </el-col>
              <el-col :span="2">
                {{ goods.saleNum }}
              </el-col>
              <el-col :span="2">
                <Status :goods="goods" />
              </el-col>
              <el-col :span="2">
                <div class="table-operate">
                  <el-button type="primary" link size="small" v-if="tableBtn('audit', goods)" @click="clickReApply(goods)"
                    >审核
                  </el-button>
                  <el-button type="primary" link size="small" v-if="tableBtn('pass', goods)" @click="openBatch('pass', goods)"
                    >通过
                  </el-button>
                  <el-button type="primary" link size="small" v-if="tableBtn('log', goods)" @click="openLog(goods)"
                    >日志
                  </el-button>
                  <el-button type="primary" link size="small" v-if="tableBtn('overrule', goods)" @click="overruleGoods(goods)"
                    >驳回
                  </el-button>
                  <el-button
                    type="primary"
                    link
                    size="small"
                    v-if="tableBtn('quash', goods)"
                    @click="openOperate('overruleCancel', goods)"
                    >撤销驳回
                  </el-button>
                  <el-button type="primary" link size="small" v-if="tableBtn('logoff', goods)" @click="openBatch('down', goods)"
                    >下架
                  </el-button>
                  <el-button type="primary" link size="small" v-if="tableBtn('reListed', goods)" @click="openBatch('up', goods)"
                    >上架
                  </el-button>
                  <el-button type="primary" link size="small" v-if="tableBtn('edit', goods)" @click="clickEdit(goods)"
                    >编辑
                  </el-button>
                  <!-- 查看预览 -->
                  <el-button type="primary" link size="small" @click="toPathPreview(goods)">查看预览</el-button>
                </div>
              </el-col>
            </el-row>
            <div class="remark" v-if="goods.productStatus == 6">
              <div class="label">备注：</div>
              <div>
                {{ goods.newOverruleReason }}
              </div>
            </div>
          </div>
        </el-checkbox-group>
      </div>
      <div class="pagination">
        <el-pagination
          v-model:current-page="paramsForm.page"
          v-model:page-size="paramsForm.size"
          :page-sizes="[10, 20, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @change="init"
        />
      </div>
    </template>
    <!-- 批量修改名称弹窗 -->
    <el-dialog
      v-model="visible"
      width="500"
      modal-class="manage-dialog"
      align-center
      center
      :show-close="false"
      @close="closeReset"
    >
      <template #header>
        {{ formConfigs[modalType].title }}
      </template>
      <el-form :model="form" ref="formRef" :label-position="formConfigs[modalType].align">
        <el-form-item
          v-for="item in formConfigs[modalType].list"
          :prop="item.field"
          :key="item.field"
          :label="item.label"
          :rules="item.rules"
        >
          <el-input v-model="form[item.field]" :placeholder="item.placeholder">
            <template #suffix>
              <span class="tip">{{ form[item.field] ? form[item.field].length : 0 }}/32</span>
            </template>
          </el-input>
          <span class="tip">{{ item.tip }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="confirm"> 保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 日志弹窗 -->
    <el-dialog v-model="logVisible" modal-class="log-dialog" width="900" align-center center>
      <template #title>
        <div class="log-title">
          <CustomTitle title="商品操作日志" />
        </div>
      </template>
      <GoodsDetail v-for="goods in goodsList" :goods="goods" :defaultImage="defaultImage" @openArea="openArea" />
      <div class="blank"></div>
      <div class="list">
        <div class="line" v-for="item in goodsList[0].list" :key="item.logId">
          {{ item.logDesc }}
          <div>
            操作人：{{ item.createBy }}<span>{{ item.createTime }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 运营地区抽屉 -->
    <el-drawer
      v-model="areaDrawer"
      :size="800"
      :with-header="false"
      modal-class="area-drawer"
      :direction="direction"
      :before-close="cancelAreaEdit"
    >
      <div class="area-container">
        <div class="left">
          <div class="area-title">运营区域设置</div>
          <div class="search-input">
            <el-input
              placeholder="请输入关键词"
              v-model="keywords"
              @blur="getAreaList"
              @keyup.enter="getAreaList"
              :suffix-icon="Search"
            />
          </div>
          <div class="arae">
            <el-scrollbar>
              <div class="province">
                <div
                  :class="{ 'province-acive': active.id == item.id }"
                  v-for="item in area"
                  :key="item.id"
                  @click="activeProvince(item)"
                >
                  {{ item.name }}
                </div>
              </div>
            </el-scrollbar>
            <el-scrollbar>
              <el-tree
                ref="areaRef"
                :data="active.children"
                :props="{ label: 'name' }"
                show-checkbox
                node-key="id"
                @check="checkChange"
              />
            </el-scrollbar>
          </div>
        </div>
        <el-divider direction="vertical" />
        <div class="right">
          <div class="right-title">已选字段</div>
          <div class="right-list">
            <el-scrollbar>
              <div v-for="item in checkedAreaList" :key="item.areaId">
                <div class="province">
                  {{ item.name || item.areaName }}
                  <el-icon>
                    <DeleteFilled @click="delProvince(item.areaId)" />
                  </el-icon>
                </div>
                <div class="city" v-for="city in item.children" :key="city.areaId">
                  <div>
                    {{ city.name || city.areaName }}
                    <el-icon>
                      <CloseBold @click="delCity(item.areaId, city.areaId)" />
                    </el-icon>
                  </div>
                  <div v-for="area in city.children" class="area" :key="area.areaId">
                    {{ area.name || area.areaName }}
                    <div>
                      限制商家数:
                      <el-input v-model="area.planNum" size="small" controls-position="right" placeholder="请输入" />
                      <el-icon>
                        <CloseBold @click="delArea(item.areaId, city.areaId, area.areaId)" />
                      </el-icon>
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>
          <div class="area-btn">
            <el-button @click="cancelAreaEdit">取消</el-button>
            <el-button type="primary" @click="confirmSaveArea">保存</el-button>
          </div>
        </div>
      </div>
    </el-drawer>
    <!-- 分类 -->
    <el-drawer v-model="classifyDrawer" modal-class="classify-drawer" :with-header="false">
      <div class="title">批量修改商品分类</div>
      <div class="classify-head">
        <span>分类名称</span>
        <span>操作</span>
      </div>
      <el-tree style="max-width: 600px" :data="paramsOption.classify" class="tree">
        <template #default="{ data }">
          {{ data.name }}
          <el-checkbox
            :model-value="classify"
            v-if="data.children.length == 0"
            @change="changeClassify"
            :true-value="data.categoryId"
          />
        </template>
      </el-tree>
      <div class="classify-btn">
        <el-button @click="classifyDrawer = false">取消</el-button>
        <el-button type="primary" @click="saveClassify">保存</el-button>
      </div>
    </el-drawer>
    <!-- 二次确认 -->
    <Confirmation
      v-model:visible="sureVisibel"
      :title="warnConfig[operate.type]"
      :btnText="operate.type === 'read' ? '我已知晓' : '确定'"
      @comfirm="operateConfirm[operate.type]"
    />
    <!-- 驳回弹窗 -->
    <Overrule v-model:visible="overruleVisible" :overruleDetail="overruleDetail" @confirmOverrule="confirmOverrule">
      <template #default>
        <GoodsDetail :goods="overruleDetail" :defaultImage="defaultImage" @openArea="openArea" />
      </template>
    </Overrule>
    <!-- 通过/下架/上架弹窗 -->
    <BatchModal
      v-model:batchVisible="batchVisible"
      :confirmBatch="confirmBatch"
      :goods-list="goodsList"
      :batchType="batchType"
      @area="openArea"
    >
      <template #list>
        <div class="batch-list">
          <GoodsDetail v-for="goods in goodsList" :goods="goods" :defaultImage="defaultImage" @openArea="openArea" />
        </div>
      </template>
    </BatchModal>
    <!--  批量驳回  -->
    <el-dialog v-model="show" modal-class="log-dialog" width="900" align-center center title="商品批量审核驳回">
      <template #title>
        <div class="log-title">
          <CustomTitle title="商品批量审核驳回" />
        </div>
      </template>
      <div class="goods-list">
        <GoodsDetail
          style="margin-bottom: 10px"
          v-for="item in checkedData"
          :key="item.productId"
          :goods="item"
          :defaultImage="defaultImage"
          @openArea="openArea"
        />
      </div>
      <div class="blank"></div>
      <el-form-item label="备注" class="remark">
        <el-input v-model="remark" class="areaText" :rows="10" type="textarea" placeholder="请输入" />
        <div class="red">温馨提示：请详细描述驳回原因，以便商家明确知晓并更改商品信息 ~ ~</div>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="show = false">取消</el-button>
          <el-button type="primary" @click="confirmRule"> 确认驳回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { RefreshRight, Search } from "@element-plus/icons-vue";
import { nameConfig, warnConfig } from "./config";
import { getDicts } from "@/api/system/dict/data";
import {
  getCategoryTree,
  getLog,
  getProductList,
  updateProductCategory,
  shelves,
  soldOut,
  batchUpdateName,
  audit,
  cancelOverrule,
  saveArea,
  getCount,
  getGoodsArea,
  setArea,
  getArea,
  getPlatformAttributeList,
  exportFactory
} from "@/api/products/manage";
import { ElMessage } from "element-plus";
import defaultImage from "@/assets/images/products/default.png";
import { useRouter } from "vue-router";
import GoodsDetail from "./components/GoodsDetail.vue";
import BatchModal from "./components/BatchModal.vue";
import Status from "./components/Status.vue";
import { useRoute } from "vue-router";
import Overrule from "./components/Overrule.vue";
import Confirmation from "./components/Confirmation.vue";
import PlatformAttribute from "./components/platformAttribute.vue";
import { getFileDownload } from "@/utils/index.js";

const route = useRoute();

const router = useRouter();

const paramsRef = ref(null);
const show = ref(false);

const keywords = ref("");
const checkAll = ref(false);
const isIndeterminate = ref(false);
const checkedList = ref([]);
const checkedData = ref([]);
const remark = ref("");
const formRef = ref();
const form = ref({});
const modalType = ref("");
const visible = ref(false);
const logVisible = ref(false);
const areaDrawer = ref(false);
const sureVisibel = ref(false);
const classifyDrawer = ref(false);
const overruleVisible = ref(false);
const batchVisible = ref(false);
const exportLoding = ref(false);
const areaRef = ref(null);
const paramsForm = ref({
  page: 1,
  size: 20,
  productStatus: 0,
  sourceType: 1
});
const batchType = ref("");
const area = ref();
const operate = ref({
  title: "",
  desc: ""
});
const goodsList = ref([]);
const paramsOption = ref({});
const total = ref(0);
const data = ref([]);
const classify = ref([]);
const customTypeList = [
  { dictValue: 1, dictLabel: "不可定制" },
  { dictValue: 2, dictLabel: "可定制" }
];

//跳转预览页
const toPathPreview = row => {
  const routeUrl = router.resolve({ path: "/products/manage/preview", query: { id: row?.tempLinkId || row?.productId } });
  window.open(routeUrl.href, "_blank");
};

/**
 * 审核
 */
const clickReApply = row => {
  const routeUrl = router.resolve({
    path: "/products/manage/re-applay",
    query: { productId: row.productId, redirect: "/products/manage", tabs: paramsForm.value.productStatus }
  });
  window.open(routeUrl.href, "_blank");
};

/**
 * 编辑
 */
const clickEdit = row => {
  const routeUrl = router.resolve({
    path: "/products/manage/edit",
    query: { productId: row.productId, redirect: "/products/manage", tabs: paramsForm.value.productStatus }
  });
  window.open(routeUrl.href, "_blank");
};
/**
 * 地址栏是否带回了tabs参数
 */
const setRouteTabs = () => {
  if (route.query.tabs) {
    const tabs = route.query.tabs;
    paramsForm.value.productStatus = Number(tabs);
  }
};
/**
 * 切换tab标签的回调
 */
const handleClick = () => {
  data.value = [];
  checkAll.value = false;
  isIndeterminate.value = false;
  checkedList.value = [];
  init();
};
const counts = ref({
  reviewedNum: 0,
  downdNum: 0,
  listingNum: 0,
  comingDownNum: 0,
  delistNum: 0,
  allNum: 0,
  platformAttributeNum: 0
});

const editAreaId = ref("");
const formConfigs = { nameConfig };
const tempArea = ref([]);
/**
 * 表头上方按钮显示控制
 */
const isShow = btnType => {
  let operaterBtn = {
    name: [1, 2, 3, 4, 5, 6, 7], //批量修改名字
    area: [2, 6, 3, 4, 5], // 批量修改地区
    shelves: [5], // 上架
    logoff: [3], // 下架
    quash: [4], // 撤销下架
    del: [1, 7],
    pass: [2],
    classify: [2, 6, 3, 4, 5]
  };
  if (paramsForm.value.productStatus === 0) return true;
  return typeof operaterBtn[btnType] == "boolean"
    ? operaterBtn[btnType]
    : operaterBtn[btnType].includes(paramsForm.value.productStatus);
};
/**
 * 表格操作按钮控制
 */
const tableBtn = (btnType, goods) => {
  /**
   * userInfo.value.tenantTypeCode: 1:工厂 2:商家
   * operaterBtn key:按钮类型 value:是否显示 为数组:部分显示 数组值为 tabs页name值;
   */
  if (goods.isWillDelist == 1) {
    if (btnType == "log") return true;
  } else {
    let operaterBtn = {
      log: true, // 日志
      overrule: [2], // 驳回
      logoff: [3], // 下架
      quash: [6], // 撤销驳回
      pass: [2],
      audit: [2],
      reListed: [5], // 上架
      del: [1, 7], // 删除
      down: [1], // 下架
      edit: [3]
    };
    return typeof operaterBtn[btnType] == "boolean" ? operaterBtn[btnType] : operaterBtn[btnType]?.includes(goods.productStatus);
  }
};
const checkedAreaList = ref([]);
const active = ref({});

/**
 * 根据id数组递归筛选节点,组成选中的树
 */
function filterTree(tree, keys, nums) {
  if (!tree?.length) return [];
  let arr = [];
  for (let index = 0; index < tree.length; index++) {
    const planNum = nums.filter(item => item.areaId == tree[index].id)[0]?.planNum;
    const areaId = tree[index].areaId ? tree[index].areaId : tree[index].id;
    const id = tree[index].id == areaId ? null : tree[index].id;
    if (tree[index].children && tree[index].children.length) {
      if (filterTree(tree[index].children, keys, nums).length > 0) {
        arr.push({
          ...tree[index],
          children: [...filterTree(tree[index].children, keys, nums)],
          areaId,
          id
        });
      }
    } else if (keys.includes(tree[index].id)) {
      arr.push({
        ...tree[index],
        planNum,
        areaId,
        id
      });
    }
  }
  return arr;
}

/**
 * 递归获取所有子地区id
 */
const getAreaId = tree => {
  let arr = [];
  const getId = tree => {
    tree.forEach(item => {
      if (item.children && item.children.length > 0) {
        getId(item.children);
      } else {
        arr.push(item.areaId || item.id);
      }
    });
  };
  getId(tree);
  return arr;
};
/**
 * 设置树型选择
 */
const setAreaTreeKsys = keys => {
  if (!areaRef.value) return;
  areaRef.value.setCheckedKeys(keys);
};
/**
 * 切换省
 */
const activeProvince = item => {
  active.value = { ...item };
  setAreaTreeKsys(getAreaId(checkedAreaList.value));
};
/**
 * 删除地区选项
 */
const delArea = (provinceId, cityId, areaId) => {
  checkedAreaList.value.forEach(province => {
    if (province.areaId == provinceId) {
      province.children.forEach(city => {
        if (city.areaId == cityId) {
          city.children = city.children.filter(area => area.areaId != areaId);
        }
        if (city.children.length == 0) {
          province.children = province.children?.filter(city => city.areaId != cityId);
        }
      });
      if (province.children.length == 0) {
        checkedAreaList.value = checkedAreaList.value?.filter(province => province.areaId != provinceId);
      }
    }
  });
  setAreaTreeKsys(getAreaId(checkedAreaList.value));
};
/**
 * 删除市
 */
const delCity = (provinceId, cityId) => {
  checkedAreaList.value.forEach(province => {
    if (province.areaId == provinceId) {
      province.children = province.children.filter(city => city.areaId != cityId);
    }
    if (province.children.length == 0) {
      checkedAreaList.value = checkedAreaList.value.filter(province => province.areaId != provinceId);
    }
  });
  setAreaTreeKsys(getAreaId(checkedAreaList.value));
};
/**
 * 删除省
 */
const delProvince = provinceId => {
  checkedAreaList.value = checkedAreaList.value.filter(province => province.areaId != provinceId);
  setAreaTreeKsys(getAreaId(checkedAreaList.value));
};
/**
 * 递归筛选出选中的属性
 */
const mapArea = tree => {
  let arr = [];
  const getAreaNum = tree => {
    tree.forEach(item => {
      if (item.children && item.children.length) {
        getAreaNum(item.children);
      } else {
        arr.push({ planNum: item.planNum, areaId: item.areaId });
      }
    });
  };
  if (tree) getAreaNum(tree);
  return arr;
};
/**
 * 地区选项发生改变的回调
 */
const checkChange = () => {
  if (areaRef.value.getCheckedKeys().length == 0) {
    // 当前树没有节点选中时
    checkedAreaList.value = checkedAreaList.value.filter(v => v.areaId != active.value.id);
    return;
  } else {
    const keys = areaRef.value.getCheckedKeys();
    const children = filterTree(active.value.children, keys, mapArea(checkedAreaList.value));
    const index = checkedAreaList.value.findIndex(v => v.id == active.value.id || v.areaId == active.value.id);
    if (index == -1) {
      checkedAreaList.value.push({ ...active.value, areaId: active.value.id, areaName: active.value.name, children });
    } else {
      checkedAreaList.value[index].children = children;
    }
  }
};
/**
 * 对比地区新旧数据，加删除增加字段给后端
 */
const compareArea = (newArea, oldArea) => {
  // 给树型结构添加deleteTag字段
  const addDeleteTag = tree => {
    return tree.map(v => {
      if (v.children) {
        return { ...v, deleteTag: 0, children: addDeleteTag(v.children) };
      } else {
        return { ...v, deleteTag: 0 };
      }
    });
  };
  let add = [];
  const mergeTree = (newTree, oldTree) => {
    if (!oldTree) return newTree;
    for (let item of oldTree) {
      const newItem = newTree.filter(v => v.areaId == item.areaId)[0];
      if (newItem) {
        item.planNum = newItem.planNum;
        if (newItem.children && item.children) {
          mergeTree(newItem.children, item.children);
        }
      } else {
        const del = tree => {
          tree.children.forEach(v => {
            v.deleteTag = 1;
            if (v.children && v.children.length) {
              del(v);
            }
          });
          return tree;
        };
        item.deleteTag = 1;
        if (item.children && item.children.length) item = del(item);
      }
    }
    newTree.forEach((item, index) => {
      const oldItem = oldTree.filter(v => v.areaId == item.areaId)[0];
      if (oldItem) {
        if (item.children && oldItem.children) {
          mergeTree(item.children, oldItem.children);
        }
      } else {
        if (!add.filter(v => item.id == v.id)[0]) {
          oldTree[index] = item;
        }
      }
    });
    return oldTree;
  };
  return mergeTree(newArea, addDeleteTag(oldArea));
};
/**
 * 保存地区
 */
const confirmSaveArea = async () => {
  let paramsData = [];
  if (editAreaId.value) {
    // 单个
    const res = await setArea({ productId: editAreaId.value, list: compareArea(checkedAreaList.value, tempArea.value) });
    if (res.code == 200) areaDrawer.value = false;
    editAreaId.value = null;
    init();
  } else {
    // 批量
    paramsData = checkedList.value.map(v => ({ productId: v, areaList: mapArea(checkedAreaList.value) }));
    const res = await saveArea(paramsData);
    if (res.code == 200) areaDrawer.value = false;
    init();
  }
  ElMessage.success("操作成功");
};
const overruleDetail = ref({});
/**
 * 打开驳回商品弹窗
 */
const overruleGoods = goods => {
  overruleDetail.value = { ...goods };
  overruleVisible.value = true;
};
/**
 * 重置搜索条件
 */
const reset = () => {
  paramsForm.value = {
    size: paramsForm.value.size,
    page: paramsForm.value.page,
    sourceType: paramsForm.value.sourceType,
    productStatus: paramsForm.value.productStatus
  };
  init();
};
/**
 * 批量操作弹窗
 */
const openBatch = (type, goods) => {
  batchType.value = type;
  if (goods || checkedList.value.length) {
    if (goods) {
      goodsList.value = [goods];
    } else {
      goodsList.value = data.value.filter(v => checkedList.value.includes(v.productId));
    }
    batchVisible.value = true;
  } else {
    return ElMessage.error("请选择商品");
  }
};
/**
 * 批量弹窗确认
 */
const confirmBatch = {
  close: res => {
    if (res.code == 200) {
      batchVisible.value = false;
      getListCount();
      init();
      ElMessage.success("操作成功");
    }
  },
  pass: async () => {
    const res = await audit({ productIds: goodsList.value.map(v => v.productId), auditingStatus: 1 });
    confirmBatch.close(res);
  },
  down: async form => {
    const res = await soldOut({ productIds: goodsList.value.map(v => v.productId), ...form });
    confirmBatch.close(res);
  },
  up: async () => {
    // 上架
    const res = await shelves({ productIds: goodsList.value.map(v => v.productId) });
    confirmBatch.close(res);
  }
};
/**
 * 确认驳回
 */
const confirmOverrule = async () => {
  const res = await audit({
    productIds: [overruleDetail.value.productId],
    auditingStatus: 2,
    newOverruleReason: overruleDetail.value.newOverruleReason
  });
  ElMessage.success("操作成功");
  if (res.code == 200) overruleVisible.value = false;
  init();
  getListCount();
};
/**
 * 切换批量分类
 */
const changeClassify = value => {
  classify.value = value;
};
/**
 * 保存商品分类
 */
const saveClassify = async () => {
  const res = await updateProductCategory({
    categoryId: classify.value,
    productId: checkedList.value
  });
  ElMessage.success("保存成功");
  init();
  if (res.code == 200) classifyDrawer.value = false;
};
/**
 * 重置批量操作表单
 */
const closeReset = () => {
  formRef.value.resetFields();
};
/**
 * 打开批量操作弹窗
 */
const showModal = title => {
  if (checkedList.value == 0) return ElMessage.error("请选择商品");
  visible.value = true;
  modalType.value = title;
};
/**
 * 批量修改名字保存按钮的回调
 */
const confirm = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      const res = await batchUpdateName({ ...form.value, productId: checkedList.value });
      init();
      if (res.code == 200) visible.value = false;
    }
  });
};
const operateConfirm = {
  read() {
    console.log("知道了");
  },
  returned() {
    console.log("返还");
  },
  overruleCancel: async () => {
    // 取消驳回
    const res = await cancelOverrule(operate.value.productId);
    ElMessage.success("操作成功");
    init();
    getListCount();
    if (res.code == 200) sureVisibel.value = false;
  }
};
/**
 * 选中
 */
const checked = () => {
  checkAll.value = checkedList.value.length == data.value.length;
  isIndeterminate.value = checkedList.value.length != data.value.length && checkedList.value.length != 0;
  console.log(checkedList.value, 9999);
};
/**
 * 设置全选
 */
const setCheckAll = () => {
  console.log(data.value);
  checkedList.value = checkAll.value ? data.value.map(item => item.productId) : [];
  isIndeterminate.value = false;
};

/**
 * 查看日志
 */
const openLog = async goods => {
  const res = await getLog({ productId: goods.productId });
  goodsList.value = [{ list: res.data, ...goods }];
  logVisible.value = true;
};
/**
 * 获取列表选项字典
 * @param {*} dictType 字典类型
 */
const getDict = async dictType => {
  const res = await getDicts(dictType);
  paramsOption.value[dictType] = res.data;
};
/**
 * 修改地区
 */
const openArea = async productId => {
  if (productId || checkedList.value.length) {
    checkedAreaList.value = [];
    setAreaTreeKsys([]);
    if (productId) {
      editAreaId.value = productId;
      const res = await getGoodsArea({ productId });
      checkedAreaList.value = res.data;
      tempArea.value = JSON.parse(JSON.stringify(res.data));
      setAreaTreeKsys(getAreaId(res.data));
    }
    areaDrawer.value = true;
  } else {
    return ElMessage.error("请选择商品");
  }
};
// 驳回
const handleOverrule = () => {
  if (checkedList.value.length === 0) return ElMessage.error("请勾选需要批量驳回的商品后点击此按钮!");
  const objectMap = new Map(data.value.map(obj => [obj.productId, obj]));
  checkedData.value = checkedList.value.map(productId => objectMap.get(productId)).filter(obj => obj !== undefined);
  show.value = true;
};

// 确认批量驳回
const confirmRule = async () => {
  console.log(checkedList.value);
  await audit({
    productIds: checkedList.value,
    auditingStatus: 2, // 2驳回 1 通过
    newOverruleReason: remark.value
  });
  ElMessage.success("操作成功");
  show.value = false;
  await init();
  await getListCount();
};
/**
 * 在弹窗中设置地区后更新
 */
const setModalArea = data => {
  if (overruleVisible.value) {
    overruleDetail.value = data.records.filter(v => v.productId == log.value.productId)[0];
  } else if (batchVisible.value) {
    const ids = goodsList.value.map(v => v.productId);
    goodsList.value = data.records.filter(v => ids.includes(v.productId));
  }
};
const countKey = {
  2: "reviewedNum",
  6: "downdNum",
  3: "listingNum",
  4: "comingDownNum",
  5: "delistNum",
  0: "allNum"
};
/**
 * 初始化列表
 */
const init = async () => {
  if ([7].includes(paramsForm.value.productStatus)) return;
  const categoryId = paramsForm.value.categoryId
    ? paramsForm.value.categoryId[paramsForm.value.categoryId.length - 1]
    : paramsForm.value.categoryId;
  const paramData = {
    ...paramsForm.value,
    productStatus: [0, 4].includes(paramsForm.value.productStatus) ? "" : paramsForm.value.productStatus,
    categoryId,
    isWillDelist: paramsForm.value.productStatus == 4 ? 1 : undefined,
    buinessAddressIdList: paramsForm.value?.buinessAddressIdList?.map(item => item.join(","))
  };
  const res = await getProductList(paramData);
  total.value = res.data.total;
  data.value = res.data.records;
  // 设置数量
  counts.value[countKey[paramsForm.value.productStatus]] = res.data.total;
  // 更新弹窗数据
  setModalArea(res.data);
};
/**
 * 获取数量
 */
const getListCount = async () => {
  const res = await getCount();
  counts.value = { ...counts.value, ...res.data };
};
/**
 * 打开二次确认弹窗
 */
const openOperate = (type, goods) => {
  operate.value = { ...operate.value, type, ...goods, title: warnConfig[type] };
  sureVisibel.value = true;
};
/**
 *  获取分类
 */
const getClassify = async () => {
  const res = await getCategoryTree();
  paramsOption.value.classify = res.data;
};
const cancelAreaEdit = () => {
  areaDrawer.value = false;
  editAreaId.value = null;
};
const getAreaList = async () => {
  const res = await getArea(keywords.value);
  area.value = res.data;
};
/**
 * 获取平台属性
 */
const getPlatformAttribute = async () => {
  try {
    const res = await getPlatformAttributeList();
    counts.value.platformAttributeNum =
      Number(res.data.unmodifyStastsProductNum) +
      Number(res.data.modifyStastsProductNum) +
      Number(res.data.noFillOutStastsProductNum);
  } catch (error) {
    console.log(error);
  }
};
// 导出上传数据
const handleDown = async () => {
  exportLoding.value = true;
  exportFactory({}).then(res => {
    getFileDownload(res, "商品上传数据.xlsx");
    exportLoding.value = false;
  });
};
onMounted(() => {
  setRouteTabs();
  getClassify();
  const dictArr = ["shop_product_custom_type", "shop_product_style", "bool_type", "shop_is_model", "shop_product_custom_type"];
  dictArr.forEach(item => {
    getDict(item);
  });
  init();
  getAreaList();
  getListCount();
  getPlatformAttribute();
});
</script>

<style lang="scss" scoped>
@mixin flex-end {
  display: flex;
  justify-content: end;
}

@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

@mixin flex-align {
  display: flex;
  align-items: center;
}

.page {
  height: calc(100vh - 84px);
  overflow-y: scroll;
}

.params-form {
  background: #f6f8fa;
  margin-bottom: 10px;

  ::v-deep(.el-form) {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    column-gap: 76px;
  }

  .form-btn {
    @include flex-end;
  }

  .space {
    flex: 1;
    display: flex;
    gap: 10px;
  }
}

.operate {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;

  ::v-deep(.el-input) {
    width: 400px;
    position: absolute;
    right: 0;
  }
}

::v-deep(.el-tabs__header) {
  margin-bottom: var(--margin-bottom);
}

.pagination {
  margin-top: 20px;
  @include flex-end;
}

.sticky {
  position: sticky;
  top: -20px;
  background: white;
  z-index: 99;
}

.table-head {
  background: #f2f6fc;
  align-items: center;
  height: 40px;
  color: #4e5969;
  margin-bottom: 10px;
  font-size: 14px;

  .el-col:nth-child(1) {
    display: flex;
    align-items: center;

    .all {
      width: 40px;
      @include flex-center;
    }

    .image-title {
      display: inline-block;
      width: 98px;
    }
  }
}

.table-list {
  .el-checkbox-group {
    line-height: unset;
    font-size: unset;
  }

  .el-col {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #e1e6ed;
    border-left: 1px solid #e1e6ed;
    color: #4e5969;
    font-size: 14px;
    justify-content: center;
  }

  .el-col:nth-child(1) {
    justify-content: start;
  }

  .el-col:last-child {
    border-right: 1px solid #e1e6ed;
  }

  .goods {
    margin-bottom: 12px;

    .business-name {
      display: flex;
      justify-content: space-between;
      background: #f2f6fc;
      font-size: 14px;
      line-height: 40px;
      padding-right: 10px;
      color: #007dff;

      .name {
        flex: 1;
        display: flex;
        margin-right: 50px;
      }

      > div:nth-child(2) {
        cursor: pointer;
        @include flex-align;
        gap: 10px;
      }

      .all {
        min-width: 40px;
        @include flex-center;

        ::v-deep(.el-checkbox__label) {
          padding: 0;
        }
      }
    }

    .remark {
      font-size: 14px;
      display: flex;
      border: 1px solid #ebeef5;
      border-top: none;
      padding: 12px;

      .label {
        color: #86909c;
        white-space: nowrap;
      }
    }
  }

  .table-operate {
    display: grid;
    grid-template-columns: 1fr;
    width: 100%;
    row-gap: 10px;

    ::v-deep(.el-button) {
      margin: 0 auto;
    }
  }

  .image {
    width: 80px;
    height: 80px;
    border-radius: 4px;
    margin: 0 18px 0 40px;
  }

  .info {
    color: #86909c;
    font-size: 12px;
    line-height: 20px;

    .red {
      color: red;
    }
  }
}

.tip {
  color: #86909c;
  font-size: 10px;
  line-height: 18px;
}

::v-deep(.is-error) {
  .tip {
    display: none;
  }
}

.size {
  display: flex;
  gap: 10px;
  line-height: 26px;

  img {
    width: 80px;
    height: 80px;
  }
}

.log-title {
  padding-left: 24px;
}

// .goods-detail {
//   display: flex;
//   gap: 20px;
//   line-height: 2;

//   img {
//     width: 150px;
//     height: 150px;
//     border-radius: 4px;
//   }

//   >div {
//     width: 100%;
//   }

//   .goods-name {
//     font-size: 18px;
//     color: #007dff;
//   }

//   .goods-info {
//     text-align: left;
//     position: relative;
//     width: 100%;

//     .area {
//       color: #007dff;
//       cursor: pointer;
//       position: absolute;
//       bottom: 0;
//       right: 0;

//       .el-tag {
//         margin-left: 8px;
//       }
//     }
//   }
// }

.blank {
  height: 10px;
  background: #eef1f4;
  margin: 20px 0;
}

.list {
  height: 450px;
  overflow-y: scroll;

  .line {
    padding: 0 24px;
    display: flex;
    height: 52px;
    line-height: 52px;
    justify-content: space-between;
    border-bottom: 1px solid #eeeeee;

    > div {
      color: #000000;
    }

    span {
      color: #86909c;
      margin-left: 40px;
    }
  }
}

// 变更明细
.alter-tab {
  display: flex;

  > div {
    width: 100px;
    height: 30px;
    border: 1px solid #dcdcdc;
    color: #000000;
    line-height: 30px;
    text-align: center;
  }
}

// 区域抽屉
.area-container {
  height: 100%;
  display: flex;

  .el-divider {
    margin: unset;
  }

  .left,
  .right {
    flex: 1;
  }

  > div {
    height: 100%;
  }

  .left {
    padding: 20px 20px 0 0;

    .search-input {
      margin: 12px 0;
      padding: 0 20px;
    }

    .area-title {
      padding: 0 20px;
    }

    .arae {
      height: calc(100% - 77px);
      display: flex;

      .city,
      .province {
        font-size: 14px;

        > div {
          height: 40px;
          line-height: 40px;
        }
      }

      .city-item {
        padding-left: 20px;
      }

      .province {
        width: 150px;

        > div {
          padding-left: 20px;
        }

        .province-acive {
          color: #007dff;
          background: #f4f6f8;
        }
      }

      .el-scrollbar:nth-child(2) {
        flex: 1;
        background: #f4f6f8;
      }
    }
  }

  .right {
    padding: 20px;

    .right-title {
      margin-top: 36px;
      color: #4e5969;
      font-size: 14px;
    }

    .right-list {
      height: calc(100% - 100px);

      .province {
        height: 40px;
        background: #f4f6f8;
        @include flex-align;
        justify-content: space-between;
        padding: 0 10px;
        font-size: 14px;
        margin-top: 20px;

        .el-icon {
          color: #909399;
        }
      }

      .city {
        padding: 0 10px;
        font-size: 14px;

        > div {
          @include flex-align;
          justify-content: space-between;
          font-size: 12px;
          height: 40px;
        }

        .area {
          color: #86909c;

          > div {
            @include flex-align;
            gap: 14px;
          }
        }

        .el-input {
          width: 70px;
        }
      }
    }

    .area-btn {
      margin-top: 10px;
      @include flex-center;
    }
  }
}

.classify-head {
  @include flex-align;
  justify-content: space-between;
  height: 40px;
  background: #f2f6fc;
  margin: 20px 0;
  padding: 0 20px;
}

.areaText {
  background: #f2f3f5;
}

.red {
  color: red;
}

.remark {
  padding: 0 20px;
}

.alert {
  @include flex-align;
  width: calc(100% - 40px);
  min-height: 54px;
  margin: 0 0 20px;
  background: #ffd9c2;
  border-radius: 6px;

  .el-icon {
    color: #e37318;
    margin: 0 10px;
  }
}
</style>
<style lang="scss">
.head-tip {
  width: 300px;
}

.manage-dialog {
  .el-input__wrapper {
    background: #f2f3f5;
  }
}

.area-drawer {
  .el-drawer__body {
    padding: 0;
  }
}

.area-drawer,
.classify-drawer {
  .el-drawer.rtl {
    border-radius: 10px 0 0 10px;
  }
}

.area-drawer {
  .el-tree-node__content {
    height: 40px;
    background: #f4f6f8;
  }
}

.classify-drawer {
  .el-tree-node__content > label.el-checkbox {
    position: absolute;
    right: 20px;
  }

  .classify-btn {
    position: absolute;
    bottom: 20px;
    display: flex;
    width: 100%;
    justify-content: center;
  }
}

.batch-list {
  .goods-detail {
    margin-bottom: 20px;
  }
}

.goods-list {
  max-height: 400px;
  overflow: auto;
}
</style>
